package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.commons.template.HuanXinTemplate;
import com.tanhua.commons.template.SmsTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.Settings;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mogo.CommonLikeUser;
import com.tanhua.domain.vo.CommonLikeUserVO;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.SettingsVo;
import com.tanhua.domain.vo.UserInfoVo;
import com.tanhua.dubbo.api.*;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoService {
    @Reference
    private FriendApi friendApi;

    @Reference
    private UserLikeApi userLikeApi;
    @Reference
    private UserApi userApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Autowired
    private SmsTemplate smsTemplate;
    @Reference
    private BlackListApi blackListApi;

    @Reference
    private QuestionApi questionApi;

    @Reference
    private SettingsApi settingsApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
/*    public User finUserByToken(String token) {
        //从redis中获取当前用户信息
        String userJson = redisTemplate.opsForValue().get("TOKEN_" + token);
        if (userJson==null){
            return null;
        }
        User user = JSON.parseObject(userJson, User.class);
//客户端访问一次，就给redis里的用户信息续期一小时

        redisTemplate.opsForValue().set("TOKE_"+token,userJson, Duration.ofHours(1));

        return user;
    }*/


    public ResponseEntity findUserInfo(Long id) {

        //查询id对应的用户信息userInfo
        UserInfo userInfo = userInfoApi.findById(id);
        //把结果转换成App需要的数据userInfovo
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        if (userInfo.getAge() != null) {
            userInfoVo.setAge(String.valueOf(userInfo.getAge()));
        }
        //返回结果
        return ResponseEntity.ok(userInfoVo);


    }

    public ResponseEntity updateUserInfo(UserInfo userInfo
    ) {
        //根据token获取当前用户
        User user = UserHolder.getUser();

        //把user的id设置到userInfo对象
        userInfo.setId(user.getId());
        //把userInfo更新到数据库
        userInfoApi.update(userInfo);
        //返回结果

        return ResponseEntity.ok(null);
    }

    public ResponseEntity findSettings() {
        //1\ 获取当前用户
        User user = UserHolder.getUser();

        //2 查询陌生人问题
        Question question = questionApi.findByUserId(user.getId());

        //3 查询通知设置
        Settings settings = settingsApi.findByUserId(user.getId());

        //4 构造返回值
        SettingsVo vo = new SettingsVo();

        //4.1 封装联系人问题
        if (question != null) {
            vo.setStrangerQuestion(question.getTxt());
        }
        //4.2 封装通知设置
        if (settings != null) {
            //如果查询到了通知设置 ，加载这些设置
            BeanUtils.copyProperties(settings, vo);

        } else {
            //如果查询到了通知配置，加载这些配置
            vo.setGonggaoNotification(true);
            vo.setLikeNotification(true);
            vo.setPinglunNotification(true);

        }
        //  设置手机号
        vo.setPhone(user.getMobile());
        return ResponseEntity.ok(vo);
    }

    public ResponseEntity findBlackList(int page, int pageSize) {

        //获取当前用户
        User user = UserHolder.getUser();

        //查看当前用户的黑名单列表
        IPage<UserInfo> iPage = blackListApi.findByUserId(page, pageSize, user.getId());

        //构造返回值
        PageResult<UserInfo> vo = new PageResult<>();
        vo.setCounts((int) iPage.getTotal());
        vo.setPage(page);
        vo.setPages((int) iPage.getPages());
        vo.setPagesize(pageSize);
        vo.setItems(iPage.getRecords());
        return ResponseEntity.ok(vo);

    }

    public ResponseEntity removeBlackList(Long blackUserId) {
        //获取当前用户
        //User user = UserHolder.getUser();
        Long userId = UserHolder.getUserId();
        //移除黑名单
        blackListApi.delete(userId, blackUserId);

        return ResponseEntity.ok(null);
    }

    public ResponseEntity updateQuestion(String content) {
        //获取当前用户
        Long userId = UserHolder.getUserId();
        //查询当前用户的陌生人问题
        Question question = questionApi.findByUserId(userId);

        //设置陌生人问题
        if (question != null) {
            //如果当前用户设置过陌生人问题，就修改
            question.setTxt(content);
            questionApi.update(question);
        } else {
            question = new Question();
            question.setTxt(content);
            question.setUserId(userId);
            questionApi.save(question);
        }
        return ResponseEntity.ok(null);
    }

    public ResponseEntity saveSettings(Settings settings) {
        //获取当前用户
        Long userId = UserHolder.getUserId();
        //查询当前用户的通知设置
        Settings userSettings = settingsApi.findByUserId(userId);
        if (userSettings == null) {
            //没有查询到通知设置，则新增设置
            settings.setUserId(userId);
            settingsApi.save(settings);
        } else {
            //查询到了通知设置，则修改设置
            settings.setUserId(userSettings.getUserId());
            settingsApi.update(settings);


        }

        return ResponseEntity.ok(null);
    }

    public ResponseEntity sendVerificationCode() {
        //当前用户查询
        User user = UserHolder.getUser();
        //向用户发送验证码
        //String code = smsTemplate.sendSms(user.getMobile());
        String code = "123456";
        //把验证码放到redis中 时间5 分钟
        redisTemplate.opsForValue().set("CODE_" + user.getMobile(), code, Duration.ofMinutes(5));

        //返回响应结果
        return ResponseEntity.ok(null);

    }

    public ResponseEntity checkVerificationCode(String verificationCode) {
        //查询当前用户
        User user = UserHolder.getUser();

        //查看验证码真实性
        String code = redisTemplate.opsForValue().get("CODE_" + user.getMobile());

        Map<String, Object> map = new HashMap<>();
        //校验验证码
        if (code != null && code.equals(verificationCode)) {
            //验证码正确
            redisTemplate.delete("CODE_" + user.getMobile());
            map.put("verification", true);
        } else {
            map.put("verification", false);
        }
        return ResponseEntity.ok(map);
    }

    public ResponseEntity updateMobile(String newPhone) {
        //获取当前用户
        User user = UserHolder.getUser();
        //2. 更新手机号：只需要根据id更新mobile，
        // 不需要处理password字段，created/updated自动处理了
        user.setMobile(newPhone);
        userApi.update(user);
        return ResponseEntity.ok(null);
    }

    /**
     * 我的-喜欢、粉丝、相互喜欢数量
     * GET /users/counts
     */
    public ResponseEntity userLikeCounts() {
       //获取当前用户
        Long userId = UserHolder.getUserId();
        //调用api 查询喜欢数量
        long likeCount = userLikeApi.queryLikeCount(userId);
        //调用api 查询粉丝数量
        long fansCount = userLikeApi.queryFansCount(userId);
        //调用api 查询相互喜欢数量
        long friendsCount = userLikeApi.queryFriendsCount(userId);
        //构造返回值
        HashMap<String, Object> map = new HashMap<>();
           map.put("loveCount",likeCount);
                   map.put("fanCount",fansCount);
                   map.put("eachLoveCount",friendsCount);

       return ResponseEntity.ok(map);
    }
    /**
     * 我的-喜欢、粉丝、相互喜欢 分页列表
     * GET /users/friends/:type
     * @param type 类型 1互相关注(相互喜欢)  2我关注(我喜欢的)  3粉丝(喜欢我的)  4谁看过我
     * @param page 页码
     * @param pagesize 查询几条
     */
    public ResponseEntity userLikeList(Integer type, int page, int pagesize) {
        //获取当前用户
        Long userId = UserHolder.getUserId();
        // //2. 根据type(1互相关注(相互喜欢)  2我关注(我喜欢的)  3粉丝(喜欢我的)  4谁看过我)统计不同结果
        PageResult<CommonLikeUser> pageResult=null;
      if (type==1){
          //互相喜欢
          pageResult = userLikeApi.queryFriendsList(userId, page, pagesize);
      }else if(type == 2){
          //我喜欢的
          pageResult = userLikeApi.queryLikeList(userId, page, pagesize);
      } else if(type == 3){
          //粉丝
          pageResult = userLikeApi.queryFansList(userId, page, pagesize);
      } else if(type == 4){
          //谁看过我
          pageResult = userLikeApi.findVisitorList(userId, page, pagesize);
      }
      //转换成vo
        List<CommonLikeUser> commonUserList = pageResult.getItems();
        List<CommonLikeUserVO> voList = new ArrayList<>();
        for (CommonLikeUser commonLikeUser : commonUserList) {
            CommonLikeUserVO vo = new CommonLikeUserVO();
            UserInfo userInfo = userInfoApi.findById(commonLikeUser.getTargetUserId());
            BeanUtils.copyProperties(userInfo,vo);
            vo.setMatchRate(commonLikeUser.getScore().intValue());
            voList.add(vo);
        }
        //构造返回值
        PageResult<CommonLikeUserVO> voPageResult = new PageResult<>();
        BeanUtils.copyProperties(pageResult,voPageResult);
        voPageResult.setItems(voList);

        return ResponseEntity.ok(voPageResult);
    }
    /**
     * 我的-粉丝-喜欢
     * POST /users/fans/:uid
     */
    public ResponseEntity likeFans(Long fansId) {
        //删除粉丝对当前用户的喜欢
        userLikeApi.delete(fansId,UserHolder.getUserId());
        //把两者的好友关系记录好友表中
        friendApi.addFriend(UserHolder.getUserId(),fansId);

        //3. 把好友关系注册到环信。注意：好友双方都必须已经在环信注册过，否则好友关系添加失败
        //huanXinTemplate.addContactUser(UserHolder.getUserId(), targetId);
        return ResponseEntity.ok(null);
    }
}
